﻿using ResxHelper.Logic.Actions;
using ResxHelper.Object;
using System.Collections.Generic;
using System.IO;

namespace ResxHelper.Logic
{
    public static class FileHelper
    {
        /// <summary>
        /// Exports multiple files to provided directory
        /// </summary>
        /// <param name="files">Collection of resource files</param>
        /// <param name="directoryPath">Directory to save to</param>
        /// <param name="type">File format in which to save</param>
        /// <param name="option">Output option. Default is to output zip file only.</param>
        /// <returns></returns>
        public static bool Export(List<ResourceFile> files, string directoryPath, ResourceType type, ExportMultipleOption option = ExportMultipleOption.ZipOnly)
        {
            var paths = new List<string>();

            // process each file
            const string fileBase = "{0}\\{1}";
            foreach (var file in files)
            {
                var path = string.Format(fileBase, directoryPath, file.GetFileNameWithoutExtension());
                path = string.Format("{0}.{1}", path, ResourceFile.GetExtension(type));
                paths.Add(path);

                SaveAs(file, path);
            }

            // if a zip wasn't requested, then we're done
            if (option != ExportMultipleOption.FilesAndZip && option != ExportMultipleOption.ZipOnly) return true;

            // save zip
            SaveZip(paths, directoryPath, option == ExportMultipleOption.ZipOnly); // zip only will delete files after the zip is saved
            
            return true;
        }

        public static void SaveAs(ResourceFile file, string savePath)
        {
            var type = SaveResourceType(savePath);
            SaveActionInvoker.Save(file, type, savePath);
        }

        public static void SaveZip(IEnumerable<string> filePaths, string directoryPath, bool deleteFiles)
        {
            var request = new SaveZipRequest(filePaths, directoryPath, deleteFiles);
            SaveActionInvoker.Save(request, SaveFileType.Zip, directoryPath);
        }

        public static SaveFileType SaveResourceType(string path)
        {
            var ext = Path.GetExtension(path);
            if (string.IsNullOrEmpty(ext)) return SaveFileType.CsvString;

            SaveFileType type;
            switch (ext)
            {
                case ".csv":
                    type = SaveFileType.CsvString;
                    break;
                case ".resx":
                    type = SaveFileType.ResourceFile;
                    break;
                case ".xls":
                    type = SaveFileType.Excel;
                    break;
                default:
                    throw new FileLoadException(string.Format("Unsupported File Type {0}", ext));
            }

            return type;
        }
    }
}
